import { defineStore } from 'pinia';
import {computed, ref} from 'vue';
export const useCounterStore = defineStore('counter', () => {
//   const count = ref(0)
//   const doubleCount = computed(() => count.value * 2)
//   function increment() {
//     count.value++
//   }

//   return { count, doubleCount, increment }


//定义购物车列表
const cartList=ref([]);
//订单列表
const orderList=ref([]);
//加入购物车
const addItem=(payload)=>{
    const index=cartList.value.findIndex(item=>item.id==payload.id);
    if(index>-1){
        cartList.value[index].count++;
    }
    else{
        cartList.value.push({
            ...payload,
            count:1,
            checked:false,
        })
    }
}
//删除购物车
const deleteItem=(id)=>{
    cartList.value=cartList.value.filter(item=>item.id!=id);
}
//购物车总数量
const toatlCount=computed(()=>{
    let res=0;
    cartList.value.forEach(item=>{
        res+=item.count;
    })
    return res;
})
//购物车总价格
const totalPrice=computed(()=>{
    let res=0;
    cartList.value.forEach(item=>{
        if(item.checked){
            res+=item.count*item.price;
        }
    })
    return res.toFixed(2);
})
//订单
const addOrder=(payload)=>{
    cartList.value.findIndex(item=>item.id==payload.id);
}

return {cartList,orderList,addItem,addOrder,deleteItem,toatlCount,totalPrice}
},{
    persist:true,
})